<template>
  <div class="orders-history">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">订单历史</h1>
        <p class="page-desc">查看和管理您的交易订单历史记录</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="refreshData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
        <el-button @click="exportOrders">
          <el-icon><Download /></el-icon>
          导出记录
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><Document /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.totalOrders }}</div>
            <div class="stat-label">总订单数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon success">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.filledOrders }}</div>
            <div class="stat-label">已成交</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon warning">
            <el-icon><CircleClose /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.canceledOrders }}</div>
            <div class="stat-label">已取消</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon info">
            <el-icon><Money /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">${{ formatNumber(statistics.totalVolume) }}</div>
            <div class="stat-label">总交易量</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon danger">
            <el-icon><Coin /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">${{ formatNumber(statistics.totalFees) }}</div>
            <div class="stat-label">总手续费</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon" :class="statistics.totalPnl >= 0 ? 'success' : 'danger'">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value" :class="statistics.totalPnl >= 0 ? 'positive' : 'negative'">
              {{ statistics.totalPnl >= 0 ? '+' : '' }}${{ formatNumber(statistics.totalPnl) }}
            </div>
            <div class="stat-label">总盈亏</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <template #header>
        <div class="filter-header">
          <span>筛选条件</span>
          <el-button size="small" text @click="resetFilters">重置</el-button>
        </div>
      </template>
      
      <el-form :model="queryParams" inline class="filter-form">
        <el-form-item label="交易对">
          <el-select v-model="queryParams.symbol" style="width: 150px" @change="loadOrders">
            <el-option label="全部" value="all" />
            <el-option label="BTCUSDT" value="BTCUSDT" />
            <el-option label="ETHUSDT" value="ETHUSDT" />
            <el-option label="SOLUSDT" value="SOLUSDT" />
            <el-option label="ADAUSDT" value="ADAUSDT" />
          </el-select>
        </el-form-item>

        <el-form-item label="订单状态">
          <el-select v-model="queryParams.status" style="width: 120px" @change="loadOrders">
            <el-option label="全部" value="all" />
            <el-option label="已成交" value="filled" />
            <el-option label="已取消" value="canceled" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>

        <el-form-item label="交易方向">
          <el-select v-model="queryParams.side" style="width: 100px" @change="loadOrders">
            <el-option label="全部" value="all" />
            <el-option label="买入" value="buy" />
            <el-option label="卖出" value="sell" />
          </el-select>
        </el-form-item>

        <el-form-item label="订单类型">
          <el-select v-model="queryParams.type" style="width: 120px" @change="loadOrders">
            <el-option label="全部" value="all" />
            <el-option label="市价单" value="market" />
            <el-option label="限价单" value="limit" />
            <el-option label="止损单" value="stop" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleDateChange"
            style="width: 350px"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="orders-card">
      <template #header>
        <div class="orders-header">
          <span>订单记录 ({{ pagination.total }})</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索订单ID"
              style="width: 200px"
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table 
        :data="orders" 
        v-loading="loading"
        stripe
        @row-click="showOrderDetail"
        style="cursor: pointer"
      >
        <el-table-column prop="id" label="订单ID" width="120" />
        
        <el-table-column prop="symbol" label="交易对" width="100">
          <template #default="{ row }">
            <div class="symbol-cell">
              <span class="symbol-text">{{ row.symbol }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="side" label="方向" width="80">
          <template #default="{ row }">
            <el-tag :type="row.side === 'buy' ? 'success' : 'danger'" size="small">
              {{ row.side === 'buy' ? '买入' : '卖出' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="type" label="类型" width="80">
          <template #default="{ row }">
            <span class="order-type">{{ getOrderTypeText(row.type) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="quantity" label="数量" width="120" align="right">
          <template #default="{ row }">
            <span>{{ formatNumber(row.quantity) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="price" label="价格" width="120" align="right">
          <template #default="{ row }">
            <span v-if="row.price">${{ formatPrice(row.price) }}</span>
            <span v-else class="market-price">市价</span>
          </template>
        </el-table-column>

        <el-table-column prop="executedPrice" label="成交价" width="120" align="right">
          <template #default="{ row }">
            <span v-if="row.executedPrice">${{ formatPrice(row.executedPrice) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column prop="filled" label="成交量" width="120" align="right">
          <template #default="{ row }">
            <div class="filled-info">
              <span>{{ formatNumber(row.filled) }}</span>
              <span class="fill-rate" v-if="row.quantity > 0">
                ({{ ((row.filled / row.quantity) * 100).toFixed(1) }}%)
              </span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="fee" label="手续费" width="100" align="right">
          <template #default="{ row }">
            <span>${{ formatNumber(row.fee) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="pnl" label="盈亏" width="100" align="right">
          <template #default="{ row }">
            <span 
              v-if="row.pnl !== undefined" 
              :class="row.pnl >= 0 ? 'positive' : 'negative'"
            >
              {{ row.pnl >= 0 ? '+' : '' }}${{ formatNumber(row.pnl) }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            <span>{{ row.createTime }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>


  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh,
  Download,
  Document,
  CircleCheck,
  CircleClose,
  Money,
  Coin,
  TrendCharts,
  Search
} from '@element-plus/icons-vue'
import {
  fetchOrderHistory,
  getOrderStatistics,
  type OrderHistory,
  type OrderQueryParams
} from '@/mock/tradingData'

// 响应式数据
const loading = ref(false)
const orders = ref<OrderHistory[]>([])
const searchKeyword = ref('')
const dateRange = ref<[string, string] | null>(null)

// 查询参数
const queryParams = reactive<OrderQueryParams>({
  symbol: 'all',
  status: 'all',
  side: 'all',
  type: 'all',
  page: 1,
  pageSize: 20
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 统计信息
const statistics = ref({
  totalOrders: 0,
  filledOrders: 0,
  canceledOrders: 0,
  totalVolume: 0,
  totalFees: 0,
  totalPnl: 0,
  winRate: 0
})

// 生命周期
onMounted(() => {
  loadOrders()
  loadStatistics()
})

// 方法
const loadOrders = async () => {
  loading.value = true
  try {
    const params = {
      ...queryParams,
      page: pagination.page,
      pageSize: pagination.pageSize
    }
    
    const result = await fetchOrderHistory(params)
    orders.value = result.orders
    pagination.total = result.total
  } catch (error) {
    ElMessage.error('加载订单历史失败')
  } finally {
    loading.value = false
  }
}

const loadStatistics = async () => {
  try {
    const stats = await getOrderStatistics()
    statistics.value = stats
  } catch (error) {
    ElMessage.error('加载统计信息失败')
  }
}

const refreshData = () => {
  loadOrders()
  loadStatistics()
}

const resetFilters = () => {
  queryParams.symbol = 'all'
  queryParams.status = 'all'
  queryParams.side = 'all'
  queryParams.type = 'all'
  queryParams.startTime = undefined
  queryParams.endTime = undefined
  dateRange.value = null
  pagination.page = 1
  loadOrders()
}

const handleDateChange = (dates: [string, string] | null) => {
  if (dates) {
    queryParams.startTime = dates[0]
    queryParams.endTime = dates[1]
  } else {
    queryParams.startTime = undefined
    queryParams.endTime = undefined
  }
  pagination.page = 1
  loadOrders()
}

const handleSearch = () => {
  pagination.page = 1
  loadOrders()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadOrders()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadOrders()
}

const showOrderDetail = (_order: OrderHistory) => {
  ElMessage.info('订单详情功能开发中...')
}

const exportOrders = async () => {
  try {
    await ElMessageBox.confirm('确定要导出订单记录吗？', '确认导出', {
      type: 'info'
    })
    
    // 模拟导出功能
    ElMessage.success('订单记录导出成功')
  } catch {
    // 用户取消
  }
}

// 辅助方法
const formatNumber = (num: number): string => {
  return new Intl.NumberFormat('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 8
  }).format(num)
}

const formatPrice = (price: number): string => {
  return new Intl.NumberFormat('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(price)
}

const getOrderTypeText = (type: string): string => {
  const typeMap = {
    market: '市价单',
    limit: '限价单',
    stop: '止损单'
  }
  return typeMap[type as keyof typeof typeMap] || type
}

const getStatusText = (status: string): string => {
  const statusMap = {
    pending: '待成交',
    filled: '已成交',
    canceled: '已取消',
    rejected: '已拒绝'
  }
  return statusMap[status as keyof typeof statusMap] || status
}

const getStatusType = (status: string): string => {
  const typeMap = {
    pending: 'warning',
    filled: 'success',
    canceled: 'info',
    rejected: 'danger'
  }
  return typeMap[status as keyof typeof typeMap] || 'default'
}
</script>

<style lang="scss" scoped>
.orders-history {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .header-left {
    .page-title {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: #1f2937;
    }

    .page-desc {
      margin: 0;
      color: #6b7280;
      font-size: 14px;
    }
  }

  .header-right {
    display: flex;
    gap: 12px;
  }
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;

  .stat-card {
    border: none;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .stat-content {
      display: flex;
      align-items: center;
      gap: 16px;

      .stat-icon {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;

        &.total {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
        }

        &.success {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          color: white;
        }

        &.warning {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          color: white;
        }

        &.info {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          color: white;
        }

        &.danger {
          background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
          color: white;
        }
      }

      .stat-info {
        .stat-value {
          font-size: 24px;
          font-weight: 600;
          color: #1f2937;
          margin-bottom: 4px;

          &.positive {
            color: #10b981;
          }

          &.negative {
            color: #ef4444;
          }
        }

        .stat-label {
          color: #6b7280;
          font-size: 14px;
        }
      }
    }
  }
}

.filter-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .filter-form {
    margin-top: 16px;

    :deep(.el-form-item) {
      margin-bottom: 16px;
    }
  }
}

.orders-card {
  border: none;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

  .orders-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  :deep(.el-table) {
    .symbol-cell {
      .symbol-text {
        font-weight: 600;
        color: #1f2937;
      }
    }

    .order-type {
      color: #6b7280;
      font-size: 13px;
    }

    .market-price {
      color: #f59e0b;
      font-weight: 500;
    }

    .filled-info {
      .fill-rate {
        color: #6b7280;
        font-size: 12px;
        margin-left: 4px;
      }
    }

    .positive {
      color: #10b981;
      font-weight: 600;
    }

    .negative {
      color: #ef4444;
      font-weight: 600;
    }
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}

.order-detail {
  .detail-section {
    margin-bottom: 24px;

    h3 {
      margin: 0 0 16px 0;
      font-size: 16px;
      font-weight: 600;
      color: #1f2937;
      border-bottom: 1px solid #e5e7eb;
      padding-bottom: 8px;
    }

    .positive {
      color: #10b981;
      font-weight: 600;
    }

    .negative {
      color: #ef4444;
      font-weight: 600;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .orders-history {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;

    .header-right {
      width: 100%;
      justify-content: flex-end;
    }
  }

  .stats-cards {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 12px;
  }

  .filter-form {
    :deep(.el-form-item) {
      display: block;
      margin-bottom: 12px;

      .el-form-item__content {
        margin-left: 0 !important;
      }
    }
  }

  :deep(.el-table) {
    font-size: 12px;
  }
}
</style> 